<?php

namespace App\Exceptions\OrderPay;

use App\Trip\Code;
use App\Trip\Payment\PaymentBusiness;
use App\Trip\Wechat\Pay\PayRes\PayResult;
use Exception;
use Illuminate\Support\Facades\Log;

class BusinessMustBeRefundException extends Exception
{
    private PayResult $payResult;
    private string    $refund_message;

    public function __construct(PayResult $result, string $refund_message, string $message, int $code)
    {
        parent::__construct($message, $code ?: Code::BUSINESS_MUST_REFUND);
        $this->payResult      = $result;
        $this->refund_message = $refund_message;
        $this->mustRefund();
    }

    private function mustRefund()
    {
        $log_prefix = "系统业务条件不满足不能继续处理,必须退款:{$this->payResult->getOutTradeNo()}";
        try {
            $payment_attach = PaymentBusiness::parsePaymentAttach($this->payResult->getAttach());
            Log::error("{$log_prefix},业务类型:{$payment_attach->getType()}");
            $this->payResult->fail2Refund($this->refund_message);
            Log::error("支付回调业务处理失败,支付单号:{$this->payResult->getOutTradeNo()},原因:{$this->refund_message},已退款");

        } catch (Exception $exception) {
            Log::error("{$log_prefix},但退款失败了,Exception:{$exception->getMessage()}");
        }
    }

    public function getPayResult(): PayResult
    {
        return $this->payResult;
    }
}
